import { getPublicToken } from '@/api/user'
import router from '@/router'
import { setToken } from '@/utils/auth'
import store from '@/store'

// 刷新系统设置
import settings from '@/settings'
// const appId = 'mct'
// const props = window.$wujie?.props
let tokenCache = ''
export const initToken = (token) => {
  return new Promise(async (resolve) => {
    // console.log(window.$wujie?.props?.token == tokenCache)
    if (window.__POWERED_BY_WUJIE__ && window.$wujie?.props?.token !== tokenCache) {
      let res = await getPublicToken(window.$wujie?.props.token)
      if (res.success) {
        store.commit('user/SET_TOKEN', res.data.token)
        setToken(res.data.token)
        tokenCache = window.$wujie?.props.token
        resolve(res.data.token)
      }
    } else {
      resolve(token)
    }
  })
}

function init() {
  if (window.__POWERED_BY_WUJIE__) {
    store.dispatch('settings/CHANGE_SETTINGS', window.$wujie?.props?.setting)
    window.$wujie.bus.$on('theme-change', function (payload) {
      store.dispatch('settings/CHANGE_SETTINGS', payload)
    })
    window.$wujie.bus.$on('actived', function (id) {
      console.log('wujie actived apps', id)
      // console.log(window.$wujie?.props?.token, '---', tokenCache)
      store.dispatch('app/toggleDevice', window.$wujie?.props?.device)
      let currentRoute = router.currentRoute
      let { path, query, params } = currentRoute
      if (currentRoute.matched.length) {
        router.replace({
          path,
          query: {
            ...query,
            t: new Date().getTime(),
          },
          params,
        })
      }
    })
  } else {
    store.dispatch('settings/CHANGE_SETTINGS', settings)
  }
}

init()
